<template>
  <el-scrollbar class="app-tags" view-class="tags-view">
    <router-link v-for="tag in visitedViews" :key="tag.path" :to="tag.fullPath" class="tags-item">
      <span class="tag-content">
        {{ tag.title }}
        <i class="el-icon-close" @click.prevent.stop="closeSelectedTag(tag)"></i>
      </span>
    </router-link>
  </el-scrollbar>
</template>

<script lang="ts">
import { defineComponent, watch, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { TagView } from '@/store/modules/tagsView'

export default defineComponent({
  name: 'TagsView',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const visitedViews = computed(() => store.getters.visitedViews)

    const isActive = (view: TagView) => {
      return view.path === route.path
    }

    const addTags = () => {
      if (route.name) {
        store.dispatch('tagsView/addView', route)
      }
      return false
    }

    const toLastView = (view: TagView) => {
      const latestView = visitedViews.value.slice(-1)[0]
      if (latestView?.fullPath) {
        router.push(latestView.fullPath)
      } else {
        if (view.name === 'Dashboard') {
          router.replace({ path: '/redirect' + view.fullPath })
        } else {
          router.push('/')
        }
      }
    }

    const closeSelectedTag = (view: TagView) => {
      store.dispatch('tagsView/delView', view)
      if (isActive(view)) {
        toLastView(view)
      }
    }

    watch(
      () => route.name,
      () => {
        if (route.name !== 'Login') {
          addTags()
        }
      }
    )

    onMounted(() => {
      addTags()
    })

    return {
      visitedViews,
      closeSelectedTag
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/vars.scss';

.app-tags {
  height: 34px;
  line-height: 34px;
}

:deep(.tags-view) {
  display: flex;
}

.router-link-active.tags-item {
  color: $color-primary;
}

.tags-item {
  margin-left: 15px;
  flex-shrink: 0;
  font-size: $font-size-small;
  color: $color-text-regular;
  text-decoration: none;

  &:after {
    content: '';
    margin-right: 15px;
    border-right: $border-color-base;
    height: 1em;
    display: inline-block;
    vertical-align: middle;
  }
}

.tag-content {
  margin-right: -12px;
  padding: 10px 0;
  transition: margin 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);

  .el-icon-close {
    visibility: hidden;
    font-size: 12px;
  }

  &:hover {
    margin-right: 0;

    .el-icon-close {
      visibility: visible;
      transform: translateX(5px);
      transition: 0.5s;

      &:hover {
        padding: 1px;
        color: $color-white;
        background-color: $border-color-base;
        border-radius: $border-radius-circle;
      }
    }
  }
}
</style>
